package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate ;

    @Autowired
    private Client client ;

    @Autowired
    private UserInfoMapper userInfoMapper ;

    @Override
    public void getSMSCode(String phone) throws Exception {

        //1. 如果手机号为空，抛异常
        if(!StringUtils.hasLength(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        //2. 如果该手机号上一次发送验证码距离现在不到一分钟，则不允许发送短消息，抛出异常
        // ① 向redis中保存验证码，有效时长5分钟
        // ② 获取redis中这个phone作为key的value的剩余有效时长
        // ③ 5分钟 - 剩余有效时长  =   已经存在的时长
        // ④ 我们的业务逻辑是，已经存在的有效时长小于一分钟，不允许再次发短信验证码
        long total = RedisConstant.APP_LOGIN_CODE_TTL_SEC ;
        Long expire = redisTemplate.getExpire(RedisConstant.APP_LOGIN_PREFIX + phone, TimeUnit.SECONDS);
        if(total - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }

        //3. 发送短消息；并且将验证码同时保存到redis中
        //3-1. 发短消息
        String code = VerifyCodeUtil.getVerifyCode(4) ;
        sendCode(phone, code);
        //3-2. 保存到redis
        redisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX + phone,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);
    }

    @Override
    public void sendCode(String phone, String code) throws Exception {
        //1. client
        //2. request
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("阿里云短信测试");
        request.setTemplateCode("SMS_154950909");
        request.setPhoneNumbers(phone);
        request.setTemplateParam("{\"code\":\""+code+"\"}");
        //3. client.send(request)
        client.sendSms(request);
    }

    @Override
    public String login(LoginVo loginVo) {

        if(!StringUtils.hasLength(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if(!StringUtils.hasLength(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        String codeFromRedis = redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone());
        if(!StringUtils.hasLength(codeFromRedis)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        if(!loginVo.getCode().equals(codeFromRedis)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        UserInfo userInfoFromDB = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone,loginVo.getPhone()));
        if(userInfoFromDB==null){
            userInfoFromDB = new UserInfo();
            userInfoFromDB.setPhone(loginVo.getPhone());
            userInfoMapper.insert(userInfoFromDB);
        }

        if(userInfoFromDB.getStatus()== BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        return JwtUtil.createToken(userInfoFromDB.getId(), userInfoFromDB.getPhone());
    }
}
